const express = require('express');
const app = express()
const Response = require('./utils/res')
//const base = "http://localhost:9000/"
const base = "http://47.99.81.47:9000/"
const multer = require('multer');
const uuid = require('uuid');

const cors = require('cors');
app.use(cors())
const uploadTools = multer({
  storage: multer.diskStorage({ // 该存储方案将会把文件直接存入磁盘
      destination: (req, file, callback)=>{
          callback(null, 'static')
      },
      filename: (req, file, callback)=>{
          // 通过file，获取原始文件名     huangbo.jpg
          let name = file.originalname       
          // 截取源文件的后缀 .jpg  .png  ....
          let ext = name.substr(name.lastIndexOf('.'))
          // 生成一个随机文件名，调用callback返回即可
          let newName = uuid.v4() + ext
          callback(null, newName)
      }
  })
})
app.use(express.static('static'))
app.post('/upload', uploadTools.single('file'),  (req, resp)=>{
  // multer中间件将会把文件信息存入：req.files
  console.log(req.file)
  let url = base + req.file.filename
  resp.send(Response.ok(url))
})

app.listen(9000,()=>{
  console.log('文件上传服务已启动');
})